from os import stat
import cy_request
import cy_log
import cy_config
import time
import datetime
import numpy as np
np.set_printoptions(suppress=True)   # 取消科学计数法
import pandas as pd
import requests
import pandas
import json
from  MyTT import *

# 修改杠杆
def changeAllSymbolLeverage():
    cy_request.changeIeverage(cy_config.symbol)

# 得到当前价格 必须要得到 失败后重新获取
def getCurrentPrice():

    isLoopGetPrice = True

    last_price = None

    while isLoopGetPrice:

        time.sleep(cy_config.sleep_amount)

        c_last_price = cy_request.getPrice(cy_config.symbol)

        if c_last_price:

            isLoopGetPrice = False

            last_price = c_last_price

    last_price = float(last_price)

    return last_price

def list_split(items, n):
    return [items[i:i+n] for i in range(0, len(items), n)]

# 当前金额
def getBlan():

    try:
        balance_str = cy_request.getBalance()
        return balance_str

    except Exception as e:
        pass
    else:
        pass

    return 0

# 得到价格区间数组 开多区间
def getMorePrices(base_price):

    section_all_prices = []

    # 根据币种的类型来判断存在小数点后几位，在这里获取一下
    price_lenght = cy_config.buy_price_point

    c_min_end_price = base_price

    while c_min_end_price > cy_config.more_min_price:

        time.sleep(0.0001)

        c_min_end_price = c_min_end_price - c_min_end_price * (cy_config.more_interval / 100)
        
        # 如果得到的价格是已经存在的，那么就加大more_interval （因为0.1太小了）
        c_min_end_price = round(c_min_end_price, price_lenght)

        c_min_price_postion = {
            'price' : c_min_end_price,
            'is_operate' : True
        }
        print(c_min_price_postion)
        section_all_prices.insert(0, c_min_price_postion)

    middle_price = base_price

    middle_price = round(middle_price, price_lenght)

    middle_price_postion = {
        'price' : middle_price,
        'is_operate' : True
    }

    section_all_prices.append(middle_price_postion)

    c_max_start_price = base_price

    while cy_config.more_max_price > c_max_start_price:

        time.sleep(0.0001)

        c_max_start_price = c_max_start_price + c_max_start_price * (cy_config.more_interval / 100)

        c_max_start_price = round(c_max_start_price, price_lenght)

        c_min_price_postion = {
            'price' : c_max_start_price,
            'is_operate' : True
        }

        section_all_prices.append(c_min_price_postion)

    return section_all_prices

# 得到价格区间数组 开空区间
def getLessPrices(base_price):

    section_all_prices = []

    # 根据币种的类型来判断存在小数点后几位，在这里获取一下
    price_lenght = cy_config.buy_price_point

    c_min_start_price = base_price

    while c_min_start_price > cy_config.less_min_price:

        time.sleep(0.0001)

        c_min_start_price = c_min_start_price - c_min_start_price * (cy_config.less_interval / 100)
        c_min_start_price = round(c_min_start_price, price_lenght)

        c_min_price_postion = {
            'price' : c_min_start_price,
            'is_operate' : True
        }

        section_all_prices.insert(0, c_min_price_postion)

    middle_price = base_price

    middle_price = round(middle_price, price_lenght)

    middle_price_postion = {
        'price' : middle_price,
        'is_operate' : True
    }

    section_all_prices.append(middle_price_postion)

    c_max_start_price = base_price

    while cy_config.less_max_price > c_max_start_price:

        time.sleep(0.0001)

        c_max_start_price = c_max_start_price + c_max_start_price * (cy_config.less_interval / 100)

        c_max_start_price = round(c_max_start_price, price_lenght)

        c_max_price_postion = {
            'price' : c_max_start_price,
            'is_operate' : True
        }

        section_all_prices.append(c_max_price_postion)

    return section_all_prices

def getCurrentTime():
    t = time.time()
    nowTime = int(round(t * 1000))
    return str(nowTime)

# 每7天分成一个对象
def getRunTimes(start_time, lsat_send_time):
    start_time = int(start_time)
    lsat_send_time = int(lsat_send_time)

    seven_time = 7 * 24 * 60 * 60 * 1000
    
    middle_time = lsat_send_time - start_time

    times = []

    if middle_time > seven_time:
        # 大于7天 需要拆分
        # 获取需要拆分的次数
        index = middle_time / seven_time
        index = int(index)

        if middle_time % seven_time:
            index = index + 1

        for i in range(0, index):
            
            time.sleep(cy_config.min_sleep_amount)

            c_start_time = start_time + i * seven_time

            c_end_time = 0

            if i == index - 1:
                c_end_time = lsat_send_time
            else:
                c_end_time = start_time + ((i+1) * seven_time)

            postion = {
                'item_start_time' : c_start_time,
                'item_end_time' : c_end_time
            }

            times.append(postion)
    else:
        # 小于7天 不需要拆分
        postion = {
            'item_start_time' : start_time,
            'item_end_time' : lsat_send_time
        }

        times.append(postion)

    return times

# 每半天分成一个对象
def getHalfDayRunTimes(start_time, lsat_send_time, m):

    start_time = int(start_time)
    lsat_send_time = int(lsat_send_time)

    seven_time = m * 60 * 1000
    seven_time = int(seven_time)

    middle_time = lsat_send_time - start_time

    times = []

    if middle_time > seven_time:
        
        # 大于半天 需要拆分
        # 获取需要拆分的次数
        index = middle_time / seven_time
        index = int(index)

        if middle_time % seven_time:
            index = index + 1

        for i in range(0, index):
            
            time.sleep(cy_config.min_sleep_amount)

            c_start_time = start_time + i * seven_time

            c_end_time = 0

            if i == index - 1:
                c_end_time = lsat_send_time
            else:
                c_end_time = start_time + ((i+1) * seven_time)

            postion = {
                'item_start_time' : c_start_time,
                'item_end_time' : c_end_time
            }

            times.append(postion)
    else:
        # 小于半天 不需要拆分
        postion = {
            'item_start_time' : start_time,
            'item_end_time' : lsat_send_time
        }

        times.append(postion)

    return times

def seconds_to_dhms(start_time, end_time):
    seconds = (float(end_time) - float(start_time)) / 1000

    def _days(day):
        return "{}天".format(day) if day > 1 else "{}天".format(day)
    def _hours(hour):  
        return "{}小时".format(hour) if hour > 1 else "{}小时".format(hour)
    def _minutes(minute):
        return "{}分".format(minute) if minute > 1 else "{}分".format(minute)
    def _seconds(second):  
        return "{}秒".format(second) if second > 1 else "{}秒".format(second)          
    days = int(seconds // (3600 * 24))
    hours = int((seconds // 3600) % 24)
    minutes = int((seconds // 60) % 60)
    seconds = int(seconds % 60)
    if days > 0 :
        return _days(days)+_hours(hours)+_minutes(minutes)+_seconds(seconds)
    if hours > 0 :
        return _hours(hours)+_minutes(minutes)+_seconds(seconds)
    if minutes > 0 :
        return _minutes(minutes)+_seconds(seconds)
    return _seconds(seconds)

def getSymbolYK(symbol, start_time, end_time, isMore):

    postion_item = {
        'run_time_desc' : '',
        'total_price' : 0,
        'trad_order_amount' : 0
    }

    # 获取盈亏  通过成交历史查询
    # run_times = getHalfDayRunTimes(start_time, end_time, 60)

    trades = []

    # for run_ite in run_times:
    #     cc_start_time = run_ite['item_start_time']
    #     cc_lsat_send_time = run_ite['item_end_time']

    #     c_trades = cy_request.getUserTrades(symbol, cc_start_time, cc_lsat_send_time)

    #     for c_tr in c_trades:
    #         trades.append(c_tr)

    trades = cy_request.getUserTrades(symbol, start_time, end_time)

    total_price = 0

    # 区间成交数量
    amount = 0

    for trade in trades:

        side = trade['side']
        positionSide = trade['posSide']

        if isMore:
            if side == 'sell' and positionSide == 'long':
                amount = amount + 1
                realizedPnl = trade['pnl']
                total_price = total_price + float(realizedPnl)
        else:
            if side == 'buy' and positionSide == 'short':
                amount = amount + 1
                realizedPnl = trade['pnl']
                total_price = total_price + float(realizedPnl)

    start_now = float(start_time) / 1000
    start_timeArray = time.localtime(start_now)
    start_otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", start_timeArray)

    end_now = float(end_time) / 1000
    end_timeArray = time.localtime(end_now)
    end_otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", end_timeArray)

    desc = seconds_to_dhms(start_time, end_time)

    run_time_desc = '运行时间: ' + desc + '(' + start_otherStyleTime + ' ~ ' + end_otherStyleTime + ')'

    postion_item['run_time_desc'] = run_time_desc + '\n' + '区间盈亏：' + str(total_price) + ' '
    postion_item['total_price'] = total_price
    postion_item['trad_order_amount'] = amount

    return postion_item

def reload_add_time(item):
    return item['add_time']

# 得到订单
def getOrderWithOrderId(newClientOrderId, isMore):
    order = cy_request.getOrderWithId(newClientOrderId, isMore)
    return order

# 得到购买的张数 多
def getMoreQuantityWithPrice(buy_quantity_by_u, price):

    quantity = (buy_quantity_by_u * cy_config.leverage) / (float(price) * cy_config.buy_quantity_bs)
    quantity = int(quantity)

    return quantity

# 得到购买的张数 空
def getLessQuantityWithPrice(buy_quantity_by_u, price):

    quantity = (buy_quantity_by_u * cy_config.leverage) / (float(price) * cy_config.buy_quantity_bs)
    quantity = int(quantity)

    return quantity

# 检测当前价格是否可以操作
def checkQJPriceCanOperater(qj_prices, bl, isMore):

    if bl == 0:
        # 打印不要太频繁 5 秒打印一次
        curen_time = getCurrentTime()

        if float(curen_time) > cy_config.qj_pri_ent_time:

            cy_config.qj_pri_ent_time = float(curen_time) + 5 * 1000

            if isMore:
                cy_log.printAndInLog('多 初始区间：' + str(qj_prices))
            else:
                cy_log.printAndInLog('空 初始区间：' + str(qj_prices))

        return qj_prices
    else:

        interval = 0

        if isMore:
            interval = cy_config.more_interval + cy_config.more_interval * bl
        else:
            interval = cy_config.less_interval + cy_config.less_interval * bl

        interval = round(interval, 2)

        n_price_items = []

        for index in range(0, len(qj_prices)):
            
            time.sleep(cy_config.min_sleep_amount)

            jiange = index % (bl + 1)

            if jiange == 0:
                c_p_item = qj_prices[index]

                n_price_items.append(c_p_item)

        # 打印不要太频繁 5 秒打印一次
        curen_time = getCurrentTime()

        if float(curen_time) > cy_config.qj_pri_ent_time:

            cy_config.qj_pri_ent_time = float(curen_time) + 5 * 1000

            if isMore:
                cy_log.printAndInLog('多 当前网格间距：' + str(interval))
                cy_log.printAndInLog('多 新区间：' + str(n_price_items))
            else:
                cy_log.printAndInLog('空 当前网格间距：' + str(interval))
                cy_log.printAndInLog('空 新区间：' + str(n_price_items))

        return n_price_items

# 去下单 开多
def tobuy(symbol, price, quantity, newClientOrderId):
    result = cy_request.buy_order(symbol, price, quantity, newClientOrderId)
    return result

# 去下单 平多
def sellOrder(order, newClientOrderId, more_sell_increase):
    result = cy_request.sell_order(order, newClientOrderId, more_sell_increase)
    return result

# 去下单 开空
def tobuy_openLess(symbol, price, quantity, newClientOrderId):
    result = cy_request.buy_order_open_less(symbol, price, quantity, newClientOrderId)
    return result

# 去下单 平空
def sellOrder_openLess(order, newClientOrderId, less_sell_increase):
    result = cy_request.sell_order_open_less(order, newClientOrderId, less_sell_increase)
    return result

# 去下单 平多 平持仓 市价全平
def sellOrder_more_risk(symbol):
    result = cy_request.sell_order_more_risk(symbol)
    return result

# 去下单 平空 平持仓 市价全平
def sellOrder_less_risk(symbol):
    result = cy_request.sell_order_less_risk(symbol)
    return result

def rsi(df, periods = 14, ema = True):
    """
    Returns a pd.Series with the relative strength index.
    """
    close_delta = df['close'].diff()
    # Make two series: one for lower closes and one for higher closes
    up = close_delta.clip(lower=0)
    down = -1 * close_delta.clip(upper=0)
    
    if ema == True:
	    # Use exponential moving average
        ma_up = up.ewm(com = periods - 1, adjust=True, min_periods = periods).mean()
        ma_down = down.ewm(com = periods - 1, adjust=True, min_periods = periods).mean()
    else:
        # Use simple moving average
        ma_up = up.rolling(window = periods, adjust=False).mean()
        ma_down = down.rolling(window = periods, adjust=False).mean()

    rsi = ma_up / ma_down
    rsi = 100 - (100/(1 + rsi))
    return rsi

# 获取当前这跟线rsi的值
def currentRsiValue(items):
    
    try:
        closes = []

        # 从-2开始 获取80根k线

        for rsi_index in range(0, len(items)):

            time.sleep(cy_config.min_sleep_amount)

            rsi_item = items[rsi_index]

            c_close_price = rsi_item['close']

            closes.append(float(c_close_price))

        closes = pd.DataFrame(closes, columns = ['close'])
        end_ris = rsi(closes,24).iloc[-1].tolist()

        return end_ris

    except Exception as e:
        pass
    else:
        pass

# 得到当前rsi
def getRsi(symbol):

    try:
        # 如果当前时间到了这个点，就获取一下k线
        curreny_time = getCurrentTime()

        # 15分钟的时候 用48.5 5分钟的时候用 14.25
        start_time = int(curreny_time) - 14.25 * 60 * 60 * 1000

        results = cy_request.getklines(symbol, start_time, curreny_time)

        items = []

        if len(results):

            for index in range(0, len(results)):

                time.sleep(cy_config.min_sleep_amount)

                item = results[index]

                # 获取收盘和开盘价格
                open_price = item[1]
                close_price = item[4]

                highPrice = item[2]
                lowPrice = item[3]

                openTime = item[0]

                start_now = float(openTime) / 1000
                start_timeArray = time.localtime(start_now)
                start_otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", start_timeArray)

                postion = {
                    'high' : highPrice,
                    'low' : lowPrice,
                    'open' : open_price,
                    'close' : close_price,
                    'openTime' : start_otherStyleTime,
                    'symbol' : symbol
                }

                items.append(postion)

        if len(items):
            
            rsi = currentRsiValue(items)

            return rsi
    
    except Exception as e:
        pass
    else:
        pass

    return None

#获取振幅
def zhenfu(first_close_price,first_open_price):
    buy_m = float(first_close_price) / float(first_open_price)
    buy_m = buy_m - 1
    buy_m = buy_m * 100
    return buy_m

# 得到多套单 本地记录的
def getMoreTaoDanAmount():
    
    f1 = open(cy_log.base_path + 'open_more_tao_dan_amount.json',"r",encoding="utf-8")
    content = f1.read()
    content = content.replace('\"', '')
    
    if len(content):
        content = float(content)

        if content == 0:
            # 至少为1
            content = 1

        return content

    return 1

# 得到空套单 本地记录的
def getLessTaoDanAmount():
    
    f1 = open(cy_log.base_path + 'open_less_tao_dan_amount.json',"r",encoding="utf-8")
    content = f1.read()
    content = content.replace('\"', '')

    if len(content):
        content = float(content)

        if content == 0:
            # 至少为1
            content = 1

        return content

    return 1

# 保存多套单数据到本地
def saveMoreTaoDanAmountToLocal():
    try:

        with open(cy_log.base_path + 'open_more_tao_dan_amount.json', 'w', encoding='utf-8') as fp:
            json.dump(str(cy_config.more_tao_dan_amount), fp, ensure_ascii=False) # 转为json字符并且存入本地文件中
    
    except Exception as e:
        cy_log.printAndInLog_more('=========== 报错 ============')
        cy_log.printAndInLog_more('保存套单数据到本地错：' + str(e))
        cy_log.printAndInLog_more('=========== 报错 ============')
    else:
        pass

# 保存空套单数据到本地
def saveLessTaoDanAmountToLocal():
    try:

        with open('./logs/open_less_tao_dan_amount.json', 'w', encoding='utf-8') as fp:
            json.dump(str(cy_config.less_tao_dan_amount), fp, ensure_ascii=False) # 转为json字符并且存入本地文件中
    
    except Exception as e:
        cy_log.printAndInLog_less('=========== 报错 ============')
        cy_log.printAndInLog_less('保存套单数据到本地错：' + str(e))
        cy_log.printAndInLog_less('=========== 报错 ============')
    else:
        pass

# 保存多网格区间数据到本地
def saveMoreQJDataToLocal(items):
    try:

        with open(cy_log.base_path + 'open_more_qujian_data.json', 'w', encoding='utf-8') as fp:
            json.dump(items, fp, ensure_ascii=False) # 转为json字符并且存入本地文件中

    except Exception as e:
        cy_log.printAndInLog_more('=========== 报错 ============')
        cy_log.printAndInLog_more('保存区间数据到本地报错：' + str(e))
        cy_log.printAndInLog_more('=========== 报错 ============')
    else:
        pass

# 得到多网格区间数据
def getMoreQJData():
    
    f1 = open(cy_log.base_path + 'open_more_qujian_data.json',"r",encoding="utf-8")
    
    content = f1.read()
    # content = content.replace('\"', '')
    datas = json.loads(content)

    return datas

# 保存空网格区间数据到本地
def saveLessQJDataToLocal(items):
    try:
        
        with open(cy_log.base_path + 'open_less_qujian_data.json', 'w', encoding='utf-8') as fp:
            json.dump(items, fp, ensure_ascii=False) # 转为json字符并且存入本地文件中

    except Exception as e:
        cy_log.printAndInLog_more('=========== 报错 ============')
        cy_log.printAndInLog_more('保存区间数据到本地报错：' + str(e))
        cy_log.printAndInLog_more('=========== 报错 ============')
    else:
        pass

# 得到空网格区间数据
def getLessQJData():
    
    f1 = open(cy_log.base_path + 'open_less_qujian_data.json',"r",encoding="utf-8")
    
    content = f1.read()
    # content = content.replace('\"', '')
    datas = json.loads(content)

    return datas

# 得到开仓金额 本地记录的
def getOpenPrice():

    f1 = open(cy_log.base_path + 'open_price.json',"r",encoding="utf-8")
    content = f1.read()
    content = content.replace('\"', '')

    if len(content):

        content = float(content)
        return content

    return 0

# 保存开仓金额数据到本地
def saveOpenPriceToLocal():

    try:
        with open(cy_log.base_path + 'open_price.json', 'w', encoding='utf-8') as fp:
            json.dump(str(cy_config.open_total_price), fp, ensure_ascii=False) # 转为json字符并且存入本地文件中
    
    except Exception as e:
        cy_log.printAndInLog_more('=========== 报错 ============')
        cy_log.printAndInLog_more('保存开仓金额数据到本地错：' + str(e))
        cy_log.printAndInLog_more('=========== 报错 ============')
    else:
        pass


# 获取当前这跟线ccl的值
def currentCCIValue(items):
    
    try:
        closes = []
        highs = []
        lows = []

        # 从-2开始
        for rsi_index in range(0, len(items)):

            time.sleep(cy_config.min_sleep_amount)

            rsi_item = items[rsi_index]

            c_close_price = rsi_item['close']
            high = rsi_item['high']
            low = rsi_item['low']

            closes.append(float(c_close_price))
            highs.append(float(high))
            lows.append(float(low))

        end_ccl = CCI(closes, highs, lows, 60)

        return end_ccl

    except Exception as e:
        pass
    else:
        pass

def getcci(symbol):

    try:
        # 如果当前时间到了这个点，就获取一下k线
        curreny_time = getCurrentTime()

        # 15分钟的时候 用48.5 5分钟的时候用 14.25
        start_time = int(curreny_time) - 14.25 * 60 * 60 * 1000

        results = cy_request.getklines(symbol, start_time, curreny_time)

        items = []

        if len(results):

            for index in range(1, len(results)):

                time.sleep(cy_config.min_sleep_amount)

                item = results[-index]

                # 获取收盘和开盘价格
                open_price = item[1]
                close_price = item[4]

                highPrice = item[2]
                lowPrice = item[3]

                openTime = item[0]

                start_now = float(openTime) / 1000
                start_timeArray = time.localtime(start_now)
                start_otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", start_timeArray)

                postion = {
                    'high' : highPrice,
                    'low' : lowPrice,
                    'open' : open_price,
                    'close' : close_price,
                    'openTime' : start_otherStyleTime,
                    'symbol' : symbol
                }

                items.append(postion)

        if len(items):

            rsi = currentCCIValue(items)

            return rsi
    
    except Exception as e:
        pass
    else:
        pass

    return None

def checkCCI(symbol, isMore):

    ccis = getcci(symbol)

    last_two = ccis[-1]
    last_three = ccis[-2]

    if isMore:

        # 多相关
        if last_three < -100 and last_two > -100:
            # 开多 多单笔变大一倍
            return 1
        elif last_three > 100 and last_two < 100:
            # 止盈 多单比恢复
            return 2
    else:
        
        # 空相关
        if last_three > 100 and last_two < 100:
            # 开空 空单笔变大一倍
            return 1
        elif last_three < -100 and last_two > -100:
            # 止盈 空单笔恢复
            return 2

    return 0

# 根据k线数据获取主力方向
def checkOpenMainType(symbol):
    # 获取当前4H的K线开盘价
    # 如果当前价格大于当前K线开盘价 那么主多(空的间距和利润间距*2,恢复多的间距和利润间距)
    # 如果当前价格小于当前K线开盘价 那么主空(多的间距和利润间距*2,恢复空的间距和利润间距)
    
    try:

        # 如果当前时间到了这个点，就获取一下k线
        curreny_time = getCurrentTime()

        # 获取当前4小时的k线 所以8小时就可以了
        start_time = int(curreny_time) - 8 * 60 * 60 * 1000

        results = cy_request.getklines(symbol, start_time, curreny_time)

        items = []

        if len(results):

            for index in range(0, len(results)):

                time.sleep(0.001)

                item = results[index]

                # 获取收盘和开盘价格
                open_price = item[1]
                close_price = item[4]

                highPrice = item[2]
                lowPrice = item[3]

                openTime = item[0]

                start_now = float(openTime) / 1000
                start_timeArray = time.localtime(start_now)
                start_otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", start_timeArray)

                postion = {
                    'high' : highPrice,
                    'low' : lowPrice,
                    'open' : open_price,
                    'close' : close_price,
                    'openTime' : start_otherStyleTime,
                    'symbol' : symbol
                }

                items.append(postion)

        if len(items):

            # 如果当前价格大于当前K线开盘价 那么主多(空的间距和利润间距*2,恢复多的间距和利润间距)
            # 如果当前价格小于当前K线开盘价 那么主空(多的间距和利润间距*2,恢复空的间距和利润间距)
            currentK = items[0]

            current_open_price = currentK['open']
            current_close_price = currentK['close']

            if float(current_close_price) > float(current_open_price):
                # 主多
                return 1
            elif float(current_close_price) < float(current_open_price):
                # 主空
                return 2
    
    except Exception as e:
        pass
    else:
        pass

    return 0

def hasRisk(symbol, isMore):
    
    cy_request.initMyRisk()

    more_risks = []

    local_symbol = cy_config.symbol

    if '-' in local_symbol:
        pass
    else:
        local_symbol = local_symbol.replace('USDT', '-USDT')

    for risk in cy_request.my_postion_risks:
        
        time.sleep(cy_config.min_sleep_amount)

        positionSide = risk['posSide']
        symbol = risk['instId']

        if positionSide == 'long' and (local_symbol in symbol):

            more_risks.append(risk)
    
    less_risks = []

    for risk in cy_request.my_postion_risks:
        
        time.sleep(cy_config.min_sleep_amount)

        positionSide = risk['posSide']
        symbol = risk['instId']
        
        if positionSide == 'short' and (local_symbol in symbol):
            
            less_risks.append(risk)
    
    if isMore:
        if len(more_risks):
            return True
    else:
        if len(less_risks):
            return True
    
    return False

# 得到币种开多回报率
def getOpenMoreRoe(symbol):

    # 得到当前币种持仓的回报率
    cy_request.initMyRisk()

    local_symbol = symbol

    if '-' in local_symbol:
        pass
    else:
        local_symbol = local_symbol.replace('USDT', '-USDT')

    postion = {
        "roe" : 0,
        "amt" : 0,
        "my_risk_entryPrice" : 0
    }

    for risk in cy_request.my_postion_risks:

        # 获取币种开多的持仓
        my_risk_positionSide = risk['posSide']
        my_risk_symbol = risk['instId']

        # 计算当前币种持仓 的回报率是多少
        # 标记价格 也是平仓价格
        my_risk_markPrice = risk['markPx']
        # 开仓均价
        my_risk_entryPrice = risk['avgPx']
        # 持有数量
        my_risk_positionAmt = risk['pos']
        # IMR
        imr = 1 / cy_config.leverage
        # 起始保證金
        qishi_price = float(my_risk_positionAmt) * float(my_risk_entryPrice) * imr

        if my_risk_positionSide == 'long' and (local_symbol in my_risk_symbol):
            # 收益 开多
            shouyi = (float(my_risk_markPrice) - float(my_risk_entryPrice)) * float(my_risk_positionAmt)
            # 回报率
            roe = (shouyi / qishi_price) * 100
            roe = round(roe, 2)

            postion['roe'] = roe
            postion['amt'] = float(my_risk_positionAmt)
            postion['my_risk_entryPrice'] = my_risk_entryPrice

    return postion

# 得到币种开空回报率
def getOpenLessRoe(symbol):
    # 得到币种开空回报率
    cy_request.initMyRisk()

    local_symbol = symbol

    if '-' in local_symbol:
        pass
    else:
        local_symbol = local_symbol.replace('USDT', '-USDT')

    postion = {
        "roe" : 0,
        "amt" : 0,
        "my_risk_entryPrice" : 0
    }

    for risk in cy_request.my_postion_risks:
        
        # 获取币种开多的持仓
        my_risk_positionSide = risk['posSide']
        my_risk_symbol = risk['instId']

        # 计算当前币种持仓 的回报率是多少
        # 标记价格 也是平仓价格
        my_risk_markPrice = risk['markPx']
        # 开仓均价
        my_risk_entryPrice = risk['avgPx']
        # 持有数量
        my_risk_positionAmt = risk['pos']
        # IMR
        imr = 1 / cy_config.leverage
        # 起始保證金

        qishi_price = float(my_risk_positionAmt) * float(my_risk_entryPrice) * imr

        if my_risk_positionSide == 'short' and (local_symbol in my_risk_symbol):
            # 收益 开空
            shouyi = (float(my_risk_entryPrice) - float(my_risk_markPrice)) * float(my_risk_positionAmt)
            # 回报率
            roe = (shouyi / qishi_price) * 100
            roe = round(roe, 2)

            postion['roe'] = roe
            postion['amt'] = abs(float(my_risk_positionAmt))
            postion['my_risk_entryPrice'] = my_risk_entryPrice

    return postion